//var router = require('express').Rouer();
var fs = require('fs');
module.exports = function(app){
app.get('/app/createPost', function(req, res){
	var CategoryObject = AV.Object.extend("DHPostCategary");
	var query = new AV.Query(CategoryObject);
	
	query.find({
		success: function(results) {
			var LocationObject = AV.Object.extend("DHLocation");
			var locationQuery = new AV.Query(LocationObject);
			locationQuery.find({
				success : function(locationResults){
					res.render('create_post', { CategoryObjects : results , LocationObjects : locationResults});
				},
				error : function(error){
				res.render('error', { message: error.message });
				console.log('signin false: %j', error.code +" : "+ error.message);	
				
				}
			});
		},
	  	error: function(error) {
		res.render('error', { message: error.message });
		console.log('signin false: %j', error.code +" : "+ error.message);	
	  }
	});	    
});

app.get('/app/openPost', function(req, res) {

	var PostObj = AV.Object.extend("DHPostNew");
	var query = new AV.Query(PostObj);
	query.include('categoryObject');
	query.include('locationObject');
	
	query.get(req.param("postId"), {
	  success: function(postObj) {
	  
		var CatagoryObject = AV.Object.extend("DHPostCategary");
		var categoryQuery = new AV.Query(CatagoryObject);
		
		categoryQuery.find({
			success: function(results) {					
			    var geoPoint = postObj.get("geoPoint");	
			    var LocationObject = AV.Object.extend("DHLocation");	
			    
			    var locationQuery = new AV.Query(LocationObject);
			    locationQuery.find({
				    success :function(locationResults){
				    var imageFile = postObj.get("imageFile");	
				    
				    	if(imageFile != null){
				    		var url = imageFile.url();
				    		res.render('update_post', { imageFileSrc: url,PostObject: postObj, CategoryObjects: results, GeoPoint : geoPoint ,LocationObjects : locationResults});			
				    	} else {					
				    		res.render('update_post', { imageFileSrc: "", PostObject: postObj, CategoryObjects: results, GeoPoint : geoPoint, LocationObjects : locationResults });					
				    	}
				    
				    },
				    error : function(error){
				    res.render('error', { message: error.message });
				    console.log('signin false: %j', error.code +" : "+ error.message);	
				    }
			    });					
							
			  },
			  error: function(error) {
				res.render('error', { message: error.message });
				console.log('signin false: %j', error.code +" : "+ error.message);	
			  }
			});				
		
					  
	  },
	  error: function(LocationObj, error) {
		res.render('error', { message: error.message });
		console.log('signin false: %j', error.code +" : "+ error.message);
	  }
	});			
	
});

app.post('/app/createPost', function(req, res) {

    var currentUser = AV.User.current();
	var PostObject = AV.Object.extend("DHPostNew");
	var postObj = new PostObject();
		
	var catagaryObj = AV.Object.createWithoutData("DHPostCategary", req.param('categary'));
	postObj.set("categoryObject", catagaryObj);
	
	postObj.set("contentType", parseInt(req.param('contentType')));
	postObj.set("postType", parseInt(req.param('postType')));	
	postObj.set("postTitle", req.param('postTitle'));
	postObj.set("postContent", req.param('postContent'));	
	
	console.log("postLocation:%j", req.param('postLocation'));
	
	var locationObj = AV.Object.createWithoutData("DHLocation", req.param('postLocation'));
	
	
	//var locationObj = new DHLocation();
	//locationObj.id = req.param('postLocation');
	postObj.set("locationObject", locationObj);
	
	var latitude = req.param('latitude');
	var longitude = req.param('longitude');
	
	var point = new AV.GeoPoint(parseFloat(latitude), parseFloat(longitude));
	postObj.set("geoPoint", point);        
	
	var createrObj = AV.Object.createWithoutData("_User", currentUser.id);
	postObj.set("createrObject", createrObj);
	
	postObj.set("startTime", req.param('startTime'));
	postObj.set("endTime", req.param('endTime'));

	postObj.set("contact", req.param('contact'));
	postObj.set("postAddress", req.param('postAddress'));	

	
	var taskFile = req.files.taskFile;

	if(taskFile.size > 0){
		fs.readFile(taskFile.path, function(err, data){
		  if(err){return res.send("读取文件失败");}
		  var base64Data = data.toString('base64');
		  var avFile = new AV.File(taskFile.name, {base64: base64Data});
		  avFile.save().then(function(avFile){
			postObj.set("imageFile", avFile);
			postObj.save(null, {
				success: function(postObj) {
					var relation = locationObj.relation("posts");
					relation.add(postObj);

					locationObj.save(null, {
						success : function(locationObj){
							res.render('success', { message: '保存成功！' });
						},
						error : function(locationObj, error){
						res.render('error', { message: error.message });
						console.log('signin false: %j', error.code +" : "+ error.message);
						
						}
					});	
				},
				error: function(postObj, error) {
					res.render('error', { message: error.message });
					console.log('signin false: %j', error.code +" : "+ error.message);
				}
			});				
		  });
		});			
	
	} else {
		postObj.save(null, {
			success: function(postObj) {
				var relation = locationObj.relation("posts");
				relation.add(postObj);

				locationObj.save(null, {
					success : function(locationObj){
						res.render('success', { message: '保存成功！' });
					},
					error : function(locationObj, error){
					res.render('error', { message: error.message });
					console.log('signin false: %j', error.code +" : "+ error.message);
					
					}
				});	
			},
			error: function(postObj, error) {
				res.render('error', { message: error.message });
				console.log('signin false: %j', error.code +" : "+ error.message);
			}
		});	
	}	
	
	
	
});

app.get('/app/postList', function(req, res) {
	var page = 0;
	if(req.param("page") != undefined){
		page = parseInt(req.param("page"));
	}
	var nextPage = page + 1;
	var previousPage = page - 1;
	var skip = page * 10;
	
	var PostObject = AV.Object.extend("DHPostNew");
	var query = new AV.Query(PostObject);
	query.ascending("objectId");
	query.include('createrObject');
	query.include('locationObject');
	query.skip(skip);
	query.limit(10);	
	query.find({
		success: function(results) {			
			if(results.length > 0){
				res.render('post_list', { Posts : results, next: nextPage, previous: previousPage});
			} else {
				res.render('post_list', { Posts : results, next: 0, previous: previousPage});
			}
		},
		error: function(error) {
			res.render('error', { message: error.message });
			console.log('signin false: %j', error.code +" : "+ error.message);	
		}
	});			
	
});

app.post('/app/deletePost', function(req, res) {

	var postObj = AV.Object.createWithoutData("DHPostNew", req.param('postId'));
		postObj.destroy({
		  success: function(postObj) {
			// The object was deleted from the AVOS Cloud.
			res.send('success');
		  },
		  error: function(postObj, error) {
			res.send(error.message);
			console.log('signin false: %j', error.code +" : "+ error.message);	
		  }
	});
	
});

app.post('/app/updatePost', function(req, res) {
    var currentUser = AV.User.current();
	var postObj = AV.Object.createWithoutData("DHPostNew", req.param('postId'));
	
	var latitude = req.param('latitude');
	var longitude = req.param('longitude');
	var point = new AV.GeoPoint(parseFloat(latitude), parseFloat(longitude));
	postObj.set("geoPoint", point);
	
	postObj.set("postTitle", req.param('postTitle'));
	postObj.set("postContent", req.param('postContent'));
	
	console.log("locationid: %j", req.param('postLocation'));
	var postLocation = AV.Object.createWithoutData("DHLocation", req.param('postLocation'));
	var relation = postLocation.relation("posts");
	relation.add(postObj);

	postObj.set("location", postLocation);
	
	postObj.set("startTime", req.param('startTime'));
	postObj.set("endTime", req.param('endTime'));
		
	postObj.set("postType", parseInt(req.param('postType')));
	postObj.set("contentType", parseInt(req.param('contentType')));	
	
	postObj.set("contact", req.param('contact'));
	postObj.set("postAddress", req.param('postAddress'));	
	
	
	var postCategory = AV.Object.createWithoutData("DHPostCategary", req.param('category'));
	postObj.set("categoryObject", postCategory);	
	
	var taskFile = req.files.imageFile;
	
	if(taskFile != undefined && taskFile.size > 0){	
			
		fs.readFile(taskFile.path, function(err, data){
		  if(err){return res.send("读取文件失败");}
		  var base64Data = data.toString('base64');
		  var avFile = new AV.File(taskFile.name, {base64: base64Data});
		  avFile.save().then(function(avFile){
		  
			postObj.set("imageFile", avFile);
			postObj.save(null, {



				success: function(postObj) {
					postLocation.save();
					res.render('success', { message: '操作成功！' });
				},
				error: function(postObj, error) {
					res.render('error', { message: error.message });
					console.log('signin false: %j', error.code +" : "+ error.message);
				}
			});				
		  });
		});			
	
	} else {
	 	
		postObj.save(null, {
			success: function(postObj) {
				postLocation.save();
				res.render('success', { message: '操作成功！' });
			},
			error: function(postObj, error) {
				res.render('error', { message: error.message });
				console.log('signin false: %j', error.code +" : "+ error.message);
			}
		});	
	}
	
			
});


};